from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from.models import *
from.serializers import *

class ContentListView(APIView):
    serializer_class = ContentSerializer  # 使用章节序列化器
    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter(
                'subject_id',
                openapi.IN_QUERY,
                description="学科ID（必传）",
                type=openapi.TYPE_STRING
            )
        ],
        responses={
            200: openapi.Response("成功返回内容", openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={"content": openapi.Schema(type=openapi.TYPE_STRING)}
            )),
            400: openapi.Response("缺少subject_id"),
            404: openapi.Response("无匹配章节"),
            500: openapi.Response("文件读取失败")
        }
    )
    def get(self, request):
        subject_id = request.query_params.get('subject_id')  # 获取subject_id参数
        if not subject_id:
            return Response({'error': 'subject_id is required'}, status=status.HTTP_400_BAD_REQUEST)
        contents = Content.objects.filter(subject__id=subject_id)  # 根据subject_id过滤章节
        serializer = self.serializer_class(contents, many=True)  # 序列化章节数据
        file_path = serializer.data[0].get('file_path')  # 获取文件路径
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        return Response({"content":content, 'id':serializer.data[0].get('id')}, status=status.HTTP_200_OK)


    
